﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace DomainScan
{
    public static class Helper
    {
        /// <summary>
        /// IPAddressToULong
        /// </summary>
        /// <param name="ip"></param>
        /// <returns></returns>
        public static ulong ToULong(this IPAddress ip)
        {
            var buffer = ip.GetAddressBytes();
            var result = (ulong)(buffer[0] << 24)
                        + (ulong)(buffer[1] << 16)
                        + (ulong)(buffer[2] << 8)
                        + (ulong)(buffer[3]);
            return result;
        }

        /// <summary>
        /// ulong to IPAddress
        /// </summary>
        /// <param name="value"></param>
        /// <returns></returns>
        public static IPAddress ToIPAddress(this ulong value)
        {
            var result = new IPAddress(new[]
            {
                (byte)(value>>24),
                (byte)(value>>16),
                (byte)(value>>8),
                (byte)(value),
            });
            return result;
        }

        /// <summary>
        /// IPAddress Sub
        /// </summary>
        /// <param name="ip1"></param>
        /// <param name="ip2"></param>
        /// <returns></returns>
        public static int Sub(this IPAddress ip1, IPAddress ip2)
        {
            //var ip1id = BitConverter.ToInt32(ip1.GetAddressBytes(), 0);
            //var ip2id = BitConverter.ToInt32(ip2.GetAddressBytes(), 0);
            var b1 = ip1.GetAddressBytes();
            var b2 = ip2.GetAddressBytes();
            return (int)(ip1.ToULong() - ip2.ToULong());
        }

        /// <summary>
        /// IPAddress Add
        /// </summary>
        /// <param name="ip"></param>
        /// <param name="count"></param>
        /// <returns></returns>
        public static IPAddress Add(this IPAddress ip, int count)
        {
            ulong ipid = ip.ToULong() + (ulong)count;
            return ipid.ToIPAddress();
        }
    }
}
